import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/business/home/controller/set_moto_controller.dart';
import 'package:dmz/business/home/model/ebike_set.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/widgets/%20wheel_scroll_widget.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/tools/map/map_manger.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class MapPgaeController extends BaseController {
  late AMapController mapController;

  late EbikeSet ebikeSet; // 车辆配置信息

  LatLng? initLatLng; //初始化车辆位置

  late MotoModel data;

  Map<String, Marker> markerMap = {}; //标记点

  String initAddresss = ''; //逆地理位置

  bool actionOpen = false;

  int selectData = 3;
  int selectIndex = 0;
  List selectDatas = [3, 5, 10, 30, 100];
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    var controllered = Get.find<HomePageController>();
    data = controllered.motoList[controllered.pageIndex];
    getInitLocation();

    super.onInit();
  }

  ///获取初始位置
  getInitLocation() {
    if (Get.arguments != null) {
      getSettingInfor();
    } else {
      ebikeSet = Get.find<SetMotoController>().ebikeSet;
      didInit();
      getMotoLocation();
    }
  }

  didInit() {
    initLatLng = ebikeSet.latLng ??
        LatLng((ebikeSet.fence_center?['lat'] ?? 22.58087921142578),
            (ebikeSet.fence_center?['lng'] ?? 113.95349884033203));
    selectIndex = selectDatas
        .indexWhere((element) => element == ebikeSet.fence_radius! ~/ 1000);
    selectData = ebikeSet.fence_radius! ~/ 1000;
    var iconed = BitmapDescriptor.fromIconPath('assets/gif/location.gif');
    Marker marker = Marker(position: initLatLng!, icon: iconed);
    markerMap['setLocation'] = marker;
    actionOpen = ebikeSet.electronic_fence == 1;
    update();
  }

  getSettingInfor() {
    RequestClient().post<Map>(APIS.getSetting, data: {
      'ebike_id': data.id,
      'size': 1,
      'index': 1,
    }).then((value) async {
      ebikeSet = EbikeSet.fromJson(value?['ebike_set'] as Map<String, dynamic>);
      ebikeSet.fly_car = value?['fly_car'] ?? 0;
      ebikeSet.id = value?['ebike_id'] ?? 0;
      ebikeSet.latLng = await EMIMapManger().convertLatLng(
          ebikeSet.fence_center?['lng'], ebikeSet.fence_center?['lat']);
      if (ebikeSet.fence_center?['lng'] != 0) didInit();
      getMotoLocation();
    });
  }

  ///获取车辆位置
  getMotoLocation() {
    RequestClient().post<Map<String, dynamic>>(APIS.getMotoMsg,
        data: {'ebike_id': data.id, 'cmd': 'Location'}).then((value) async {
      debugPrint('车辆位置 --- $value');
      var latLng =
          await EMIMapManger().convertLatLng(value?['lng'], value?['lat']);
      if (initLatLng == null) {
        ebikeSet.latLng = latLng;
        // initLatLng = latLng;
        didInit();
      }
      debugPrint('车辆位置2 --- ${latLng.latitude} ${latLng.longitude}');
      addMarkerMap(latLng, 'moto');
      getLocationStr();
    });
  }

  ///地理逆编码
  getLocationStr() async {
    var data = await EMIMapManger().reverseGeocoding(initLatLng!);
    initAddresss = data['formatted_address'];
    update();
  }

  ///移动镜头
  changeCarme(double latitude, double longitude) {
    // debugPrint('当前位置返回 --- $latitude $longitude');
    var latLng = LatLng(latitude, longitude);
    CameraPosition position =
        CameraPosition(target: LatLng(latitude, longitude), zoom: 15);
    mapController.moveCamera(CameraUpdate.newCameraPosition(position));
    addMarkerMap(latLng, 'user');
  }

  ///添加大头针
  addMarkerMap(LatLng latLng, String key) async {
    var iconed = BitmapDescriptor.fromIconPath(
        'assets/images/home/main/location_image.png');
    debugPrint('添加大头针 ---------999');
    Marker marker = Marker(position: latLng, icon: iconed);
    markerMap[key] = marker;
    update();
  }

  ///范围选择
  selectDataAcrion() {
    EMILoding.showBottomWindow(
        SelectWheelWidget(
            title: '围栏半径设置',
            initIndex: selectIndex,
            count: 5,
            datas: selectDatas,
            callBack: (index, data) {
              Get.back();
              selectData = data;
              selectIndex = index;
              update();
              updataPage('fence_radius', selectData * 1000);
            }),
        isDismissible: true,
        showBack: true);
  }

  ///按钮打开
  didOpen() {
    if (!actionOpen) {
      selectIndex = 1;
      selectData = 5;
      updataPage('fence_radius', selectData * 1000);
    }
    actionOpen = !actionOpen;
    updataPage('electronic_fence', actionOpen ? 1 : 0);
    update();
  }

  updataPage(key, data) {
    RequestClient().post<Map<String, dynamic>>(APIS.updataSetting, data: {
      'ebike_id': ebikeSet.id,
      'ebike_set': {key: data}
    }).then((value) async {
      if (key == 'electronic_fence') {
        ebikeSet.electronic_fence = data;
      }
      if (key == 'fence_radius') {
        ebikeSet.fence_radius = selectData * 1000;
      }
    });
  }
}

class MapBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => MapPgaeController());
  }
}
